<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

require_once "function/user.php";
require_once "function/chat.php";

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public  static $user;
    public  static $chat;
    public  static $debug=true;
    public static function gatewayReturn($state="300",$type="", $msg = '操作成功', $data = array()){
        $data = array(
            'code' => $state,
            'type' => $type,
            'msg'   => $msg,
            'data'  => $data
        );
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    // 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次。
    //可以在这里为每一个businessWorker进程做一些全局初始化工作，例如设置定时器，初始化redis等连接等。
    public static function onWorkerStart($worker)
    {
        self::$user=  new user();
        self::$chat=  new chat();
    }
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        // Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // Gateway::sendToClient($client_id, json_encode(array('type'=>'bindsuccess','message'=>$client_id)));
        $data=[
                'client_id' => $client_id  
            ];
        Gateway::sendToClient($client_id,self::gatewayReturn(200,'init',"连接成功",$data));
        // 向所有人发送
        // Gateway::sendToAll("$client_id login\r\n");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
        // 向所有人发送 
        // Gateway::sendToAll("$client_id said $message\r\n");
        
        $data=json_decode($message,true);
        switch ($data['type']) {
            case 'login'://登录
                Gateway::bindUid($client_id, $data['uid']);
                $user=self::$user->userInfo($data['uid']);
                Gateway::sendToUid($data['uid'], self::gatewayReturn(200,'loginSuccess',"登录成功",$user));
            //   Gateway::sendToUid($data['uid'], json_encode(array('type' => 'loginSuccess', 'message' => $data['uid'] . '登录成功')));
            break;
            case 'bind'://绑定UID
                Gateway::bindUid($client_id, $data['uid']);
                $user=self::$user->userInfo($data['uid']);
                Gateway::sendToUid($data['uid'], self::gatewayReturn(200,'userInfo',"绑定成功",$user));
                self::$user->webBindUser($data);
            //   Gateway::sendToUid($data['uid'], json_encode(array('type' => 'bindSuccess', 'message' => $data['uid'] . '绑定成功')));
            //   self::$user->join_all_group($data['uid'],$client_id);
            break;
            case 'userInfo'://获取用户信息
                $uid=Gateway::getUidByClientId($client_id);
                if($uid){
                    $user=self::$user->userInfo($uid);
                    Gateway::sendToUid($data['uid'], self::gatewayReturn(200,'userInfo',"获取用户信息成功",$user));
                }else{
                    Gateway::sendToUid($data['uid'], self::gatewayReturn(400,'userInfo',"获取用户信息失败",$data));
                }
            break;
            case 'logOut'://退出登录
               Gateway::unbindUid($client_id, $data['uid']);
            break;
            case 'ping': //心跳
                $uid=Gateway::getUidByClientId($client_id);
                if(!$uid){
                    $dt=[
                        'client_id' => $client_id  
                    ];
                    if(@$data['uid']){
                        Gateway::bindUid($client_id, $data['uid']);
                        $user=self::$user->userInfo($data['uid']);
                    }else{
                        Gateway::sendToClient($client_id, self::gatewayReturn(200,'NoUid',"没有绑定UID",$data));
                    }
                }else{
                    $rt=self::$user->addOnline($uid,$data);
                }
                // Gateway::sendToCurrentClient($client_id.'测试');
            break;
            case 'pong': //心跳
                $uid=Gateway::getUidByClientId($client_id);
                if(!$uid){
                    $dt=[
                        'client_id' => $client_id  
                    ];
                    if(@$data['uid']){
                        Gateway::bindUid($client_id, $data['uid']);
                        $user=self::$user->userInfo($data['uid']);
                    }else{
                        // Gateway::sendToClient($client_id, self::gatewayReturn(200,'NoUid',"没有绑定UID",$data));
                    }
                }else{
                    if(@$data['token']){
                        $rt=self::$user->addOnline($uid,$data);
                    }
                }
                // Gateway::sendToCurrentClient($client_id.'测试');
            break;
            case 'message': //消息模块
                $dt=$data['data'];
                $uid=Gateway::getUidByClientId($client_id)??$data['uid'];
                switch ($dt['type']) {
                    case 'chatConnect': //消息连接
                        self::$chat->chatConnect($data);
                    break;
                    case 'chatOut': //退出聊天
                        self::$chat->chatOut($data);
                    break;
                    case 'chatMarkRead': //消息标记已读
                        self::$chat->chatMarkRead($data);
                    break;
                    default:
                        if(self::$debug){
                            Gateway::sendToClient($client_id, self::gatewayReturn(200,'NotKey','消息模块的Key',$data));
                        }
                    break;
                }
            break;
            default:
                if(self::$debug){
                    Gateway::sendToClient($client_id, self::gatewayReturn(200,'NotKey','没有设定的Key',$data));
                }
            break;
        }
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
    //   GateWay::sendToAll("$client_id logout\r\n");
   }
}
